package com.py.credit.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.py.credit.clean.code.IdcardValidator;
import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.constant.ApiPath;
import com.py.credit.dao.LhjcHongHeimdDao;
import com.py.credit.entity.SysUser;
import com.py.credit.service.LhjcHongHeimdService;
import com.py.framework.core.common.Page;
import com.py.framework.core.helper.UrlHelper;
import com.py.framework.core.http.HttpAgent;

@Service
public class LhjcHongHeimdServiceImpl implements LhjcHongHeimdService {

	@Autowired
	private UrlHelper urlHelper;

	@Autowired
	private LhjcHongHeimdDao lhjcHongHeimdDao;

	@Override
	public String getGzNames(String cfbm, String jclb, String jdToken) {
		String url = urlHelper.getBaseMessUrl() + ApiPath.GET_LHJC_GZ_NAMES;
		Map<String, String> params = new HashMap<String, String>(1);
		params.put("cfbm", cfbm);
		params.put("jclb", jclb);
		String result = "";
		try {
			// 发送请求
			result = HttpAgent.getInstance().sendHttpPost(url, params, jdToken);
			return JSONObject.parseObject(result, new TypeReference<RestServiceResult<String>>() {
			}).getData();
		} catch (Exception e) {
			RestServiceResult<String> data = new RestServiceResult<String>();
			data.setCode(RestServiceResult.CODE_UNKNOW);
			data.setMsg("系统异常，请稍后再试！");
			ExceptionLogger.error(
					"远程服务-获取联合奖惩规则名称调用异常！(LhjcHongHeimdServiceImpl#getGzNames) URL:" + url + "Result:" + result,
					e.getMessage(), e);
			return data.getData();
		}
	}

	@Override
	public List<LinkedHashMap> selectHongheiMdForPage(String jclb, String type, String ztmc, String bm, String flag,
			List<String> gzNameList, Page page) {
		if (jclb.equals("C")) {
			if (type.equals("C")) {
				return lhjcHongHeimdDao.selectFrHeimdForPage(ztmc, flag, gzNameList, page);
			} else {
				return lhjcHongHeimdDao.selectZrrHeimdForPage(bm, flag, gzNameList, page);
			}
		} else {
			if (type.equals("C")) {
				return lhjcHongHeimdDao.selectFrHongmdForPage(ztmc, flag, gzNameList, page);
			} else {
				return lhjcHongHeimdDao.selectZrrHongmdForPage(bm, flag, gzNameList, page);
			}
		}
	}

	@Override
	public LinkedHashMap selectHongheiMdDetail(String jclb, String type, String recordId) {
		if (jclb.equals("C")) {
			if (type.equals("C")) {
				return lhjcHongHeimdDao.selectFrHeimdDetail(recordId);
			} else {
				return lhjcHongHeimdDao.selectZrrHeimdDetail(recordId);
			}
		} else {
			if (type.equals("C")) {
				return lhjcHongHeimdDao.selectFrHongmdDeatil(recordId);
			} else {
				return lhjcHongHeimdDao.selectZrrHongmdDetail(recordId);
			}
		}
	}

	@Override
	public LinkedHashMap add(String jclb, String type, List<String> recordIdList, String jdToken, String isCheck,
			SysUser user) {
		LinkedHashMap map = new LinkedHashMap();
		// 初始化统计数据
		// 总数
		int totalCount = recordIdList.size();
		// 成功数
		int successCount = 0;
		// 比对失败数
		int compareFailedCount = 0;
		// 入库失败数
		int storageFailedCount = 0;

		for (int i = 0; i < recordIdList.size(); i++) {
			// 判断是否在其他事件库存在，如果存在，比对失败数+1，数据奖惩状态修改为比对失败
			LinkedHashMap detail = this.selectHongheiMdDetail(jclb, type, recordIdList.get(i));
			boolean isExistFlag = this.detailIsExistOtherStorage(jclb, type, detail, jdToken, isCheck,
					recordIdList.get(i));
			if (isExistFlag) {
				compareFailedCount++;
				this.modifyJcFlag(jclb, type, "B", recordIdList.get(i));
				continue;
			}

			boolean isSuccessFlag = false;

			if (type.equals("C")) {
				isSuccessFlag = this.addFrLhjcAjbh(jclb, detail, jdToken, isCheck, recordIdList.get(i),
						user.getUsername());
			} else {
				isSuccessFlag = this.addZrrLhjcAjbh(jclb, detail, jdToken, isCheck, recordIdList.get(i),
						user.getUsername());
			}

			if (!isSuccessFlag) {
				storageFailedCount++;
				this.modifyJcFlag(jclb, type, "C", recordIdList.get(i));
				continue;
			}

			this.modifyJcFlag(jclb, type, "D", recordIdList.get(i));
		}

		successCount = totalCount - compareFailedCount - storageFailedCount;

		map.put("totalCount", totalCount);
		map.put("successCount", successCount);
		map.put("compareFailedCount", compareFailedCount);
		map.put("storageFailedCount", storageFailedCount);
		return map;
	}

	@Override
	public boolean detailIsExistOtherStorage(String jclb, String type, LinkedHashMap deatil, String jdToken,
			String isCheck, String recordId) {
		String url = urlHelper.getBaseMessUrl() + ApiPath.DETAIL_IS_EXIST_OTHER_STORAGE;
		Map<String, String> params = new HashMap<String, String>(1);
		params.put("jclb", jclb);
		params.put("type", type);
		params.put("isCheck", isCheck);
		params.put("recordId", recordId);

		if (type.equals("C")) {
			params.put("ztmc", (String) deatil.get("A000001"));
		} else {
			params.put("bm", (String) deatil.get("B000002"));
		}

		String result = "";
		try {
			// 发送请求
			result = HttpAgent.getInstance().sendHttpPost(url, params, jdToken);
			return JSONObject.parseObject(result, new TypeReference<RestServiceResult<Boolean>>() {
			}).getData();
		} catch (Exception e) {
			RestServiceResult<Boolean> data = new RestServiceResult<Boolean>();
			data.setCode(RestServiceResult.CODE_UNKNOW);
			data.setMsg("系统异常，请稍后再试！");
			ExceptionLogger.error("远程服务-获取联合奖惩规则名称调用异常！(LhjcHongHeimdServiceImpl#detailIsExistOtherStorage) URL:" + url
					+ "Result:" + result, e.getMessage(), e);
			return data.getData();
		}
	}

	@Override
	public boolean addFrLhjcAjbh(String jclb, LinkedHashMap deatil, String jdToken, String isCheck, String recordId,
			String username) {
		String url = urlHelper.getBaseMessUrl() + ApiPath.ADD_LHJC_FR;
		Map<String, String> params = new HashMap<String, String>(1);
		params.put("jclb", jclb);
		params.put("tybm", (String) deatil.get("tybm"));
		params.put("qymc", (String) deatil.get("A000001"));
		params.put("tyshxydm", (String) deatil.get("A000002"));
		params.put("gsdjm", (String) deatil.get("A000003"));
		params.put("zzjgdm", (String) deatil.get("A000004"));
		params.put("gzName", (String) deatil.get("HMDMC"));
		params.put("cfqx", (String) deatil.get("YXQZ"));
		params.put("isCheck", isCheck);
		params.put("recordId", recordId);
		params.put("username", username);

		if (jclb.equals("C")) {
			params.put("ysajh", (String) deatil.get("LRMDSY"));
		}

		String result = "";
		try {
			// 发送请求
			result = HttpAgent.getInstance().sendHttpPost(url, params, jdToken);
			return JSONObject.parseObject(result, new TypeReference<RestServiceResult<Boolean>>() {
			}).getData();
		} catch (Exception e) {
			RestServiceResult<Boolean> data = new RestServiceResult<Boolean>();
			data.setCode(RestServiceResult.CODE_UNKNOW);
			data.setMsg("系统异常，请稍后再试！");
			ExceptionLogger.error(
					"远程服务-远程调用添加法人事件！(LhjcHongHeimdServiceImpl#addFrLhjcAjbh) URL:" + url + "Result:" + result,
					e.getMessage(), e);
			return data.getData();
		}
	}

	@Override
	public boolean addZrrLhjcAjbh(String jclb, LinkedHashMap deatil, String jdToken, String isCheck, String recordId,
			String username) {
		String url = urlHelper.getBaseMessUrl() + ApiPath.ADD_LHJC_ZRR;
		Map<String, String> params = new HashMap<String, String>(1);
		params.put("jclb", jclb);
		params.put("tybm", (String) deatil.get("tybm"));
		params.put("xm", (String) deatil.get("B000001"));
		params.put("bm", (String) deatil.get("B000002"));
		params.put("gzName", (String) deatil.get("DATA_CATEGORY"));
		params.put("cfqx", (String) deatil.get("EXPIRATION_DATE"));
		params.put("isCheck", isCheck);
		params.put("recordId", recordId);
		params.put("username", username);

		if (jclb.equals("C")) {
			params.put("ysajh", (String) deatil.get("CASE_NO"));
		}

		String result = "";
		try {
			// 发送请求
			result = HttpAgent.getInstance().sendHttpPost(url, params, jdToken);
			return JSONObject.parseObject(result, new TypeReference<RestServiceResult<Boolean>>() {
			}).getData();
		} catch (Exception e) {
			RestServiceResult<Boolean> data = new RestServiceResult<Boolean>();
			data.setCode(RestServiceResult.CODE_UNKNOW);
			data.setMsg("系统异常，请稍后再试！");
			ExceptionLogger.error(
					"远程服务-远程调用添加自然人事件！(LhjcHongHeimdServiceImpl#addZrrLhjcAjbh) URL:" + url + "Result:" + result,
					e.getMessage(), e);
			return data.getData();
		}
	}

	@Override
	public void modifyJcFlag(String jclb, String type, String jcFlag, String recordId) {
		if (jclb.equals("C")) {
			if (type.equals("C")) {
				lhjcHongHeimdDao.modifyFrHeimdJcFlag(jcFlag, recordId);
			} else {
				lhjcHongHeimdDao.modifyZrrHeimdJcFlag(jcFlag, recordId);
			}
		} else {
			if (type.equals("C")) {
				lhjcHongHeimdDao.modifyFrHongmdJcFlag(jcFlag, recordId);
			} else {
				lhjcHongHeimdDao.modifyZrrHongmdJcFlag(jcFlag, recordId);
			}
		}
	}

	@Override
	public LinkedHashMap addGlcfZrr(JSONArray zrrGlcfArray, String jdToken) {
		LinkedHashMap map = new LinkedHashMap();
		// 初始化统计数据
		// 总数
		int totalCount = zrrGlcfArray.size();
		// 成功数
		int successCount = 0;
		// 失败数
		int failedCount = 0;

		// 身份证号码校验
		IdcardValidator check = new IdcardValidator();

		// 护照正则校验
		String passport = "^[a-zA-Z0-9]{5,17}$";

		StringBuffer failedErrLog = new StringBuffer();

		for (int i = 0; i < zrrGlcfArray.size(); i++) {
			JSONObject zrrGlcf = zrrGlcfArray.getJSONObject(i);
			String xm = zrrGlcf.getString("xm");
			String zjtype = zrrGlcf.getString("zjtype");
			String idcard = zrrGlcf.getString("idcard");
			String position = zrrGlcf.getString("position");
			String frajbh = zrrGlcf.getString("frajbh");
			String ysajh = zrrGlcf.getString("ysajh");
			String cfqx = zrrGlcf.getString("cfqx");

			if (zjtype.equals("S")) {
				if (!check.run(idcard, "")) {
					// 身份证号码格式错误
					failedErrLog.append("第" + (i + 1) + "行身份证号码格式错误").append("</br>");
					failedCount++;
					continue;
				}
			} else if (zjtype.equals("H")) {
				// 护照校验
				if (!idcard.matches(passport)) {
					// 护照格式错误
					failedErrLog.append("第" + (i + 1) + "行护照格式错误").append("</br>");
					failedCount++;
					continue;
				}
			}

			LinkedHashMap glcf = this.addZrrLhcjGlcf(xm, zjtype, idcard, position, frajbh, ysajh, cfqx, jdToken);
			if (glcf.get("flag").equals("false")) {
				failedErrLog.append("第" + (i + 1) + "行" + glcf.get("errLog")).append("</br>");
				failedCount++;
			}
		}

		successCount = totalCount - failedCount;

		map.put("totalCount", totalCount);
		map.put("successCount", successCount);
		map.put("failedCount", failedCount);
		map.put("failedErrLog", failedErrLog.length() == 0 ? "暂无日志" : failedErrLog.toString());
		return map;
	}

	@Override
	public List<LinkedHashMap> selectUploadHongHeimdList(String tableName, List<String> gzNameList) {
		
		if(gzNameList.size() == 0) {
			return null;
		}
		
		List<String> newGzNameList = new ArrayList<>();
		
		for(String gzName : gzNameList) {
			if(gzName.contains(",")) {
				String[] gzNames = gzName.split(",");
				for(String gzNameOther : gzNames) {
					newGzNameList.add(gzNameOther);
				}
			}else {
				newGzNameList.add(gzName);
			}
		}
		
		List<LinkedHashMap> result = lhjcHongHeimdDao.selectUploadHongHeimdList(tableName, newGzNameList);
		
		return result;
	}

	@Override
	public void uploadAdd(String tableName, String jclb, String type, String recordId, String username) {
		// 判断是否在其他事件库存在
		LinkedHashMap detail = this.selectHongheiMdDetail(jclb, type, recordId);
		boolean isExistFlag = this.detailIsExistOtherStorage(jclb, type, detail, null, "Y", recordId);
		if (isExistFlag) {
			this.modifyJcFlag(jclb, type, "B", recordId);
			return;
		}

		boolean isSuccessFlag = false;

		if (type.equals("C")) {
			isSuccessFlag = this.addFrLhjcAjbh(jclb, detail, null, "Y", recordId, username);
		} else {
			isSuccessFlag = this.addZrrLhjcAjbh(jclb, detail, null, "Y", recordId, username);
		}

		if (!isSuccessFlag) {
			this.modifyJcFlag(jclb, type, "C", recordId);
			return;
		}

		this.modifyJcFlag(jclb, type, "D", recordId);
	}

	private LinkedHashMap addZrrLhcjGlcf(String xm, String zjtype, String idcard, String position, String frajbh,
			String ysajh, String cfqx, String jdToken) {
		String url = urlHelper.getBaseMessUrl() + ApiPath.ADD_ZRR_LHCJ_GLCF;
		Map<String, String> params = new HashMap<String, String>(1);
		params.put("xm", xm);
		params.put("zjtype", zjtype);
		params.put("idcard", idcard);
		params.put("position", position);
		params.put("frajbh", frajbh);
		params.put("ysajh", ysajh);
		params.put("cfqx", cfqx);

		String result = "";
		try {
			// 发送请求
			result = HttpAgent.getInstance().sendHttpPost(url, params, jdToken);
			return JSONObject.parseObject(result, new TypeReference<RestServiceResult<LinkedHashMap>>() {
			}).getData();
		} catch (Exception e) {
			RestServiceResult<LinkedHashMap> data = new RestServiceResult<LinkedHashMap>();
			data.setCode(RestServiceResult.CODE_UNKNOW);
			data.setMsg("系统异常，请稍后再试！");
			ExceptionLogger.error(
					"远程服务-远程调用添加自然人关联处罚事件！(LhjcHongHeimdServiceImpl#addZrrLhcjGlcf) URL:" + url + "Result:" + result,
					e.getMessage(), e);
			return data.getData();
		}
	}
}
